import sys
import wx
import os

from LMG.GUI.setdestdlg import SetDestDialog

from LMG.Utility.constants import *

"""
View dialogs related to specific torrent
Features:
 - stop torrent if needed
 - change destination
TODO:
 - Deatils
"""

################################################################

class TorrentDialogs:
    """
    Creates dialogs specific to an individual torrent
    """
    def __init__(self, torrent):
        self.torrent = torrent
        
    def stopIfNeeded(self, showDialog = True, singleTorrent = True):
        """
        Stop a torrent if necessary
        
        If the torrent is already stopped, return True
        """
        if not self.torrent.status.isActive():
            return True
            
        stopTorrent = False
            
        if showDialog:
            dialog = wx.MessageDialog(None, 
                                      _("Torrent must be inactive before proceeding. Do you want to stop this torrent?"), 
                                      _('Warning'), 
                                      wx.YES_NO|wx.ICON_EXCLAMATION)
            result = dialog.ShowModal()
            dialog.Destroy()

            if result == wx.ID_YES:
                stopTorrent = True
                
        if not showDialog or stopTorrent:
            # Stop the torrent, then return True
            self.torrent.actions.stop()
            return True

        return False

    def resumeCompleted(self):                
        dialog = wx.MessageDialog(None,
                                  _("Resuming a finished torrent will temporarily set the seeding rules to unlimited.\nAre you sure you want to proceed?"),
                                  _('Resume a finished torrent?'),
                                  wx.YES_NO|wx.ICON_QUESTION)
        result = dialog.ShowModal()
        dialog.Destroy()
        return result == wx.ID_YES
    
    def changeDest(self, event = None, parent = None):
        """
        Show a dialog to change a torrent's destination
        """
        if not self.stopIfNeeded():
            return

        # pop-up file dialog or dir dialog for new destination
        dialog = SetDestDialog(self.torrent, parent)
        result = dialog.ShowModal()
        dialog.Destroy()
        
        return (result == wx.ID_OK)
       
    def setDestination(self, event = None):
        """
        Set a torrent's destination
        """
        dest = self.torrent.files.dest

        sizetext = ' (' + self.torrent.getColumnText(COL_SIZE) +')'
        if dest is None:
            # Use one set of strings if setting a location to start
            filetext = _('choose file to save as') + sizetext
            dirtext = _('choose dir to save to') + sizetext
        else:
            # Use a different set of strings if we're setting a new location
            filetext = _('choose new location') + sizetext
            dirtext = _('choose new location') + sizetext
            
        defaultdir = utility.getLastDir("save")
        
        # What do we do if we don't have a default download location specified
        # and we call this from the webservice?
        ####################################################
        if sys.platform == "darwin":
            # Mac requires the original extension to be mentioned explicitly,
            # since it will override the extension with the first option (even if it's '*')
            try:
                # TODO: localise 'files' string
                extension = self.torrent.files.filename.split(".")[-1]
                orig_filetype = extension.upper() + " files|*." + extension.lower() + "|"
            except:
                orig_filetype = ""
        else:
            orig_filetype = ""


        if self.torrent.files.isFile():   #1 file for this torrent
            dialog = wx.FileDialog(None, 
                                   filetext, 
                                   defaultdir,
                                   self.torrent.files.filename, 
                                   orig_filetype + _('All Files') + ' (*.*)|*.*', 
                                   wx.SAVE)
        else:   # Directory torrent
            dialog = wx.DirDialog(None, 
                                  dirtext, 
                                  defaultdir, 
                                  style = wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON)
        dialog.Raise()
        result = dialog.ShowModal()
        if result == wx.ID_OK:
            dest = dialog.GetPath()
        dialog.Destroy()
        if result != wx.ID_OK:
            return False, dest

        if self.torrent.files.isFile():
            # If a file, get the directory we saved the file in
            lastdir = os.path.dirname(dest)
        else:
            # If a directory, just use the directory
            lastdir = dest
        utility.lastdir['save'] = lastdir
                
        self.torrent.files.changeProcDest(dest)
        
        return True, dest
